<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addFeeRule">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column label="序号" :index="indexList" type="index" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式" prop="chargeType" :formatter="funCtion" />
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteAPI(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="typ" style="float: right; margin-top: 10px;">
        <el-pagination
          :page-sizes="[2, 4, 6, 8]"
          :page-size="params.pageSize"
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 弹框 -->
    <el-dialog
      :visible="dialogVisible"
      width="680px"
      title="新增规则"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="addForm.ruleNumber" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="addForm.ruleName" />
          </el-form-item>
          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="addForm.chargeType" size="small">
              <el-radio label="duration" border>时长收费</el-radio>
              <el-radio label="turn" border>按次收费</el-radio>
              <el-radio label="partition" border>分段收费</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="flex-container" style="display:flex;justify-content:space-between">
            <el-form-item label="免费时长">
              <el-input v-model="addForm.freeDuration" />
            </el-form-item>
            <el-form-item label="收费上限">
              <el-input v-model="addForm.chargeCeiling" />
            </el-form-item>
          </div>
          <!-- el-form-item可以继续嵌套el-form-item -->
          <el-form-item label="计费规则" :prop="feeRuleProp">
            <!-- 按时长收费区域 -->
            <div v-if="addForm.chargeType==='duration'" class="duration" style="display:flex">
              每
              <el-form-item prop="durationTime">
                <el-input v-model="addForm.durationTime" class="input-box" style="width:150px" />
              </el-form-item>
              小时
              <el-form-item prop="durationPrice">
                <el-input v-model="addForm.durationPrice" class="input-box" style="width:150px" />
              </el-form-item>
              元
            </div>
            <!-- 按次收费区域 -->
            <div v-if="addForm.chargeType==='turn'" class="turn" style="display:flex">
              每次
              <el-form-item prop="turnPrice">
                <el-input v-model="addForm.turnPrice" class="input-box" style="width:150px" />
              </el-form-item>
              元
            </div>
            <!-- 按分段收费区域 -->
            <div v-if="addForm.chargeType==='partition'" class="partition">
              <div class="item" style="display:flex">
                <el-form-item prop="partitionFrameTime">
                  <el-input v-model="addForm.partitionFrameTime" class="input-box" style="width:100px" />
                </el-form-item>
                小时内,每小时收费
                <el-form-item prop="partitionFramePrice">
                  <el-input v-model="addForm.partitionFramePrice" class="input-box" style="width:100px" />
                </el-form-item>
                元
              </div>
              <div class="item" style="display:flex;margin:30px auto 0">
                每增加
                <el-form-item prop="partitionIncreaseTime">
                  <el-input v-model="addForm.partitionIncreaseTime" class="input-box" style="width:120px;" />
                </el-form-item>
                小时,增加
                <el-form-item prop="partitionIncreasePrice">
                  <el-input v-model="addForm.partitionIncreasePrice" class="input-box" style="width:120px;" />
                </el-form-item>
                元
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="comeADD">确 定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { getListAPI, getDeleteAPI, addLiatAPI } from '@/api/car'
import { utils, writeFileXLSX } from 'xlsx'

export default {
  name: 'Building',
  data() {
    return {
      ruleList: [],
      total: 0,
      params: {
        page: 1,
        pageSize: 2
      },
      dialogVisible: false, // 控制弹框关闭打开
      addForm: {
        ruleNumber: '', // 计费规则编号
        ruleName: '', // 计费规则名称
        chargeType: 'duration', // 计费规则类型 duration / turn / partition
        chargeCeiling: null,
        freeDuration: null,
        // 时长计费独有字段
        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: 'hour',
        // 按次收费独有字段
        turnPrice: null,
        // 分段计费独有字段
        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱

      }, // 计费规则表单对象
      addFormRules: {
        ruleNumber: [{ required: true, message: '请输入规则编号', trigger: 'blur' }],
        ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        chargeType: [{ required: true, message: '请选择收费类型', trigger: 'blur' }],
        durationTime: [{ required: true, message: '请输入时间', trigger: 'blur' }],
        durationPrice: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        turnPrice: [{ required: true, message: '请输入次数', trigger: 'blur' }],
        partitionFrameTime: [{ required: true, message: '请输入段内时间', trigger: 'blur' }],
        partitionFramePrice: [{ required: true, message: '请输入段内费用', trigger: 'blur' }],
        partitionIncreaseTime: [{ required: true, message: '请输入超出时间', trigger: 'blur' }],
        partitionIncreasePrice: [{ required: true, message: '请输入超出金额', trigger: 'blur' }]
      }, // 计费规则校验规则对象
      feeRuleProp: 'durationTime'

    }
  },
  watch: {
    'addForm.chargeType'(val) {
      // console.log(val)
      // 文本框一旦发生切换 清空所有的校验提示
      this.$refs.addForm.clearValidate(['turnPrice', 'durationTime', 'durationPrice', 'partitionFrameTime', 'partitionFramePrice', 'partitionIncreaseTime', 'partitionIncreasePrice'])
      if (val === 'duration') {
        this.feeRuleProp = 'durationTime'
      }
      if (val === 'turn') {
        this.feeRuleProp = 'turnPrice'
      }
      if (val === 'partition') {
        this.feeRuleProp = 'partitionFrameTime'
      }
    }
  },
  created() {
    this.addCar()
  },
  methods: {
    // 添加
    comeADD() {
      this.$refs.addForm.validate(async(flag) => {
        if (!flag) return
        await addLiatAPI(this.addForm)
        this.$message.success('添加成功')
        this.closeDialog()
        this.addCar()
      })
    },
    groupChange(val) {
      console.log(val)
    },
    // 打开弹框
    addFeeRule() {
      this.dialogVisible = true
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false
      this.$refs.addForm.resetFields()
      this.addForm.freeDuration = ''
      this.addForm.chargeCeiling = ''
    },
    // 导出Excle
    async exportToExcel() {
      const res = await getListAPI({ page: this.page, pageSize: this.pageSize })
      // 要求导出的字段名
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration']
      const list = res.data.rows.map(item => {
        // 创建一个新对象来存数据
        const obj = {}
        tableHeaderKeys.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 要导出的标头
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)']
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表 要求一个对象数组格式
      const worksheet = utils.json_to_sheet(list)
      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 计费规则
    funCtion(row, column, cellValue, index) {
      const MAP = {
        duration: '时长收费',
        turn: '按次收费',
        partition: '分段收费'
      }
      return MAP[cellValue]
    },
    // 点击切换分页
    handleCurrentChange(val) {
      this.params.page = val
      this.addCar()
    },
    // 删除计费规则
    deleteAPI(id) {
      this.$confirm('您确定要删除当前计费规则吗？', '温馨提示').then(async() => {
        await getDeleteAPI(id)
        this.$message.success('删除成功')
        this.addCar()
      }).catch(() => {})
    },
    // 处理序号问题
    indexList(row) {
      return (this.params.page - 1) * this.params.pageSize + 1 + row
    },
    // 获取数据列表
    async  addCar() {
      const res = await getListAPI(this.params)
      console.log(res)
      this.ruleList = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
